package com.ruoyi.project.module.fbsHead.controller;

import java.util.List;
import java.util.UUID;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.utils.UserUtils;
import com.ruoyi.common.utils.file.DownloadXls;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.security.ShiroUtils;
import com.ruoyi.framework.config.RuoYiConfig;
import com.ruoyi.project.common.domain.ErrorCommon;
import com.ruoyi.project.module.fbsDetail.domain.FbsDetail;
import com.ruoyi.project.module.fbsDetail.service.IFbsDetailService;
import com.ruoyi.project.module.productsUpload.domain.ProductsUpload;
import com.ruoyi.project.module.purchases.domain.Purchases;
import com.ruoyi.project.system.user.domain.User;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.constant.BusinessType;
import com.ruoyi.project.module.fbsHead.domain.FbsHead;
import com.ruoyi.project.module.fbsHead.service.IFbsHeadService;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.page.TableDataInfo;
import com.ruoyi.framework.web.domain.AjaxResult;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 转入FBS 信息操作处理
 * 
 * @author lcx
 * @date 2018-09-17
 */
@Controller
@RequestMapping("/module/fbsHead")
public class FbsHeadController extends BaseController
{
    private String prefix = "module/fbsHead";
	
	@Autowired
	private IFbsHeadService fbsHeadService;
	@Autowired
    private IFbsDetailService fbsDetailService;
	
	@RequiresPermissions("module:fbsHead:view")
	@GetMapping()
	public String fbsHead()
	{
	    return prefix + "/fbsHead";
	}
	
	/**
	 * 查询转入FBS列表
	 */
	@RequiresPermissions("module:fbsHead:list")
	@PostMapping("/list")
	@ResponseBody
	public TableDataInfo list(FbsHead fbsHead)
	{
		startPageChange();
        fbsHead.setCompanyId(UserUtils.getDepId());
        List<FbsHead> list = fbsHeadService.selectFbsHeadList(fbsHead);
		return getDataTable(list);
	}

    /**
     * 查询转入FBS签收列表
     */
    @PostMapping("/received_list")
    @ResponseBody
    public TableDataInfo list_edit_received(FbsHead fbsHead,String ids) {
        FbsDetail fbsDetail = new FbsDetail();
        fbsDetail.setHeadId(ids);
        List<FbsDetail> list = fbsDetailService.selectFbsHeadListAsEditReceived(fbsDetail);
        return getDataTable(list);
    }
	
	/**
	 * 新增转入FBS
	 */
	@GetMapping("/add")
	public String add()
	{
	    return prefix + "/add";
	}
	
	/**
	 * 新增保存转入FBS
	 */
	@RequiresPermissions("module:fbsHead:add")
	@Log(title = "转入FBS", action = BusinessType.INSERT)
	@PostMapping("/add")
	@ResponseBody
	public AjaxResult addSave(FbsHead fbsHead)
	{		
		return toAjax(fbsHeadService.insertFbsHead(fbsHead));
	}

	/**
	 * 修改转入FBS
	 */
	@GetMapping("/edit/{id}")
	public String edit(@PathVariable("id") Integer id, ModelMap mmap)
	{
		FbsHead fbsHead = fbsHeadService.selectFbsHeadById(id);
		mmap.put("fbsHead", fbsHead);
	    return prefix + "/edit";
	}
	
	/**
	 * 修改保存转入FBS
	 */
	@RequiresPermissions("module:fbsHead:edit")
	@Log(title = "转入FBS", action = BusinessType.UPDATE)
	@PostMapping("/edit")
	@ResponseBody
	public AjaxResult editSave(FbsHead fbsHead)
	{		
		return toAjax(fbsHeadService.updateFbsHead(fbsHead));
	}

	/**
	 * @Author lcx
	 * @Date 2018/9/20 11:31
	 * 批量出库
	 */
	@RequiresPermissions("module:fbsHead:edit")
	@Log(title = "fbs批量出库", action = BusinessType.UPDATE)
	@PostMapping("/edit_received")
	@ResponseBody
	public AjaxResult editSave_received(
			@RequestParam(value = "ids")String ids,
			@RequestParam(value = "actualQuantity[]")String[] actualQuantity,
			@RequestParam(value = "headIds")String headIds) {

		String id[] = ids.split(",");
		String headId[] = headIds.split(",");

		return toAjax(fbsDetailService.updatePurchasesAsReceived(id,actualQuantity,headId));
	}
	
	/**
	 * 删除转入FBS
	 */
	@RequiresPermissions("module:fbsHead:remove")
	@Log(title = "转入FBS", action = BusinessType.DELETE)
	@PostMapping( "/remove")
	@ResponseBody
	public AjaxResult remove(String ids)
	{		
		return toAjax(fbsHeadService.deleteFbsHeadByIds(ids));
	}


	/**
	 * @Author lcx
	 * @Date 2018/8/24 17:12
	 * 保存批量上传的商品
	 */
	@Log(title = "批量上传FBS", action = BusinessType.INSERT)
	@PostMapping("/uploadProduct")
	@ResponseBody
	public AjaxResult uploadProduct(@RequestParam("list") String jsonList,String name,String intoDate,
									String bz, ModelMap mmap) {

		List<FbsHead> phList = JSONObject.parseArray(jsonList, FbsHead.class);

		String download = RuoYiConfig.getProfile() + "fbs/";

		FbsHead fbsHead = new FbsHead();
        fbsHead.setName(name);
        fbsHead.setIntoDate(intoDate);
        fbsHead.setBz(bz);
        fbsHead.setId(UUID.randomUUID().toString());


        User user = ShiroUtils.getUser();
        fbsHead.setCreateId(String.valueOf(user.getUserId()));
        fbsHead.setCompanyId(String.valueOf(user.getDeptId()));

		List<ErrorCommon> errorCommon = fbsHeadService.uploadFbsHeader(phList,download,fbsHead);

		if (errorCommon.size() > 0){
			return error(120, JSON.toJSON(errorCommon).toString());
		}

		return toAjax(2);
	}

	/**
	 * 修改批量出库操作
	 */
	@RequiresPermissions("module:fbsHead:edit")
	@GetMapping("/edit_fbs_batchUrl/{ids}/{names}")
	public String edit_overseas_batch(@PathVariable("ids") String ids,
									  @PathVariable("names") String names,ModelMap mmap) {

		mmap.put("ids", ids);
		mmap.put("names", names);

		return prefix + "/edit_received";
	}

	@Log(title = "批量FBSHeader上传", action = BusinessType.IMPORT)
	@PostMapping("/FileUploadServletAsXls")
	@ResponseBody
	public AjaxResult updateExcle(User user, @RequestParam("exclefile") MultipartFile file, HttpServletRequest request) {

		try {
			String fileName = file.getOriginalFilename();
			String[] splitResult = fileName.split("\\.");
			String extension = "." + splitResult[splitResult.length - 1];
			if (!extension.equalsIgnoreCase(".xls") && !extension.equalsIgnoreCase(".xlsx") && !extension.equalsIgnoreCase(".pdf")) {
				return error();
			}
			if (!file.isEmpty()) {
				String path = FileUploadUtils.upload(RuoYiConfig.getProfile() + "fbs/", file, extension);
				return fileUrl(fileName, path);
			}
			return error();
		} catch (Exception e) {
			return error(e.getMessage());
		}
	}


	@Log(title = "换入FBS模板下载", action = BusinessType.IMPORT)
	@PostMapping("/exportDownLoadFBSXls")
	@ResponseBody
	public AjaxResult DownloadXlsAsProduct(HttpServletResponse response, String state) {

		String download = RuoYiConfig.getProfile() + "download";
		try {
			DownloadXls.downLoadFile(DownloadXls.DOWNLOADNAME_FBSHEAD, DownloadXls.DOWNLOAD_TYPE_XLSX, download, response);
			return success();
		} catch (Exception e) {
			e.printStackTrace();
			return error(e.getMessage());
		}
	}
	
}
